package com.vshop.timingtask;


import com.vshop.entity.agatewaytobeijing.JsonConstant;
import com.vshop.entity.agatewaytobeijing.Page;
import com.vshop.entity.agatewaytobeijing.syncpartner.response.OriginalPartner;
import com.vshop.entity.agatewaytobeijing.syncpartner.response.ResponseSynchronizePartner;
import com.vshop.entity.agatewaytobeijing.syncpartner.response.SynchronizePartnerData;
import com.vshop.service.agatewaytobeijing.GatewayToBeijingService;
import com.vshop.service.task.ServicePlanTaskServiceImpl;
import com.vshop.utils.MD5;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 同步企业信息
 *
 * @author lm
 * @date 2020/11/3 10:58
 */
@Configuration
@EnableScheduling
@RestController
@Slf4j
public class SyncPartnerNewTask {
    @Value("${system.autoTask}")
    private boolean autoTask;
    @Autowired
    ServicePlanTaskServiceImpl taskService;
    @Autowired
    GatewayToBeijingService toBeijingService;

    @Scheduled(cron = " 0 2 19 * * ?")
    @Async
    @GetMapping(value = "partner")
    public void execute() {
        if (autoTask) {
            syncPartner();
        }
    }

    public void syncPartner() {
        log.info("每1天早上19点执行一次的syncPartner开始执行！");

        //第一次去请求确定有多少个企业确定循环需要做多少次
        ResponseSynchronizePartner firstRequest = toBeijingService.synchronizePartner(1, 1);

        //先验证请求结果的response：如果返回的是""就可以直接返回了
        if (StringUtils.isBlank(checkResponseSynchronizePartner(firstRequest))) {
            return;
        }

        //直接取page的值，拿到一共有多少条数据 去计算需要去执行几次请求
        double total = taskService.countExecution(firstRequest.getData().getPage());

        //用一个允许控制执行请求的次数
        for (int x = 1; x <= total; x++) {
            log.info("一共：" + firstRequest.getData().getPage().getTotal_count() + "条;需执行：" + total + "次;当前是：第" + x + "次");

            //第二次去请求要获得真正的企业信息
            ResponseSynchronizePartner secondRequest = toBeijingService.synchronizePartner(x, 500);

            //先验证请求结果的response：如果返回的是""就可以直接返回了
            if (StringUtils.isBlank(checkResponseSynchronizePartner(secondRequest))) {
                return;
            }

            //这边直接直接取partners的值
            for (OriginalPartner partner : secondRequest.getData().getPartner()) {
                String partnerCode = partner.getPartner_code();

                //先去数据库查询partnerCode是不是已经存在
                Integer count = taskService.findPartnerExistOrNot(partnerCode);

                if (count <= 0) {

                    //给每个企业一个索引值
                    Integer partnerIndex = 0;
                    if (!partnerCode.equals("0")) {
                        //从partnerCode的P往后数字第一位开始算起：拿到数字后进行%运算：取余（取模）有个规律就是：左边小于右边，结果为左边，左边大于右边，看余数
                        /*partnerIndex = Integer.parseInt(partnerCode.substring(1)) % 10;*/
                        try {
                            partnerIndex = Integer.parseInt(partnerCode.substring(3)) % 10;
                        } catch (NumberFormatException e) {
                            partnerIndex = Integer.parseInt(partnerCode.substring(partnerCode.length() - 1, partnerCode.length()));
                        }

                    }

                    //给每个企业给一个token值
                    String token = MD5.calcMD5(partner.getPartner_name() + partner.getPartner_code() + partner.getSecret());
                    //入库
                    Integer insertCount = taskService.insertPartner(partnerIndex, token, partner);

                    if (insertCount < 0) {
                        continue;
                    }

                } else {
                    continue;
                }
            }
        }
        log.info("每1天早上19点执行一次的syncPartner执行结束！");
    }

    /**
     * 验证请求后的响应 ResponseSynchronizePartner
     *
     * @param response
     * @return
     */
    private String checkResponseSynchronizePartner(ResponseSynchronizePartner response) {
        //response响应就是null
        if (null == response) {
            return "";
        }

        //返回的具体的内容是空的或者没有
        if (StringUtils.isBlank(response.getCode()) || StringUtils.isBlank(response.getMessage())) {
            return "";
        }

        //返回的内容不是成功
        boolean b1 = (!JsonConstant.RET_CODE_0000.equals(response.getCode()) && !JsonConstant.RET_CODE_SUCCESS.equals(response.getMessage())) || null == response.getData();
        if (b1) {
            log.info("【同步企业】响应：" + response.getCode() + ";提示：" + response.getMessage());
            return "";
        }

        SynchronizePartnerData data = response.getData();
        if (null == data.getPage() || null == data.getPartner_num() || null == data.getPartner() || data.getPartner().isEmpty()) {
            return "";
        }

        Page page = data.getPage();
        if (StringUtils.isBlank(page.getTotal_count() + "") || page.getTotal_count() <= 0) {
            return "";
        }
        //验证没有问题
        return JsonConstant.RET_CODE_SUCCESS;
    }
}
